package org.frame.auth.token;

import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

import org.frame.auth.common.exception.BaseException;
import org.frame.auth.feign.RemoteUserService;
import org.frame.common.core.StringUtils;
import org.frame.common.core.entity.User;
import org.frame.common.core.enums.UserStatus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import lombok.extern.slf4j.Slf4j;

/**
 * 用户验证处理
 * @author ty-intasect03
 *
 */
@Slf4j
@Service
public class UserDetailsServiceImpl implements UserDetailsService {
	
	@Autowired
	private RemoteUserService remoteUserService;

	@Override
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
		User user = remoteUserService.userInfo(username);
		log.debug("用户：{}", user);
		if (StringUtils.isNull(user)) {
			log.info("登录用户：{} 不存在.", username);
			throw new UsernameNotFoundException("登录用户：" + username + " 不存在");
		} else if (UserStatus.DELETED.getCode().equals(user.getDelFlag())) {
			log.info("登录用户：{} 已被删除.", username);
			throw new BaseException("对不起，您的账号：" + username + " 已被删除");
		} else if (UserStatus.DISABLE.getCode().equals(user.getStatus())) {
			log.info("登录用户：{} 已被停用.", username);
			throw new BaseException("对不起，您的账号：" + username + " 已停用");
		}

		return createLoginUser(user);
	}

	private UserDetails createLoginUser(User user) {
		return new LoginUser(user, getMenuPermission(user));
	}
	
	private Set<String> getMenuPermission(User user) {
		Set<String> roles = new HashSet<String>();
		// 管理员拥有所有权限
		if (user.isAdmin()) {
			roles.add("*:*:*");
		} else {
			roles.addAll(selectMenuPermsByUserId(user.getUserId()));
		}
		return roles;
	}
	
	private Set<String> selectMenuPermsByUserId(Long userId) {
		Set<String> perms = remoteUserService.userPerms(userId);
		Set<String> permsSet = new HashSet<>();
		if(perms != null) {
			for (String perm : perms) {
				if (StringUtils.isNotEmpty(perm)) {
					permsSet.addAll(Arrays.asList(perm.trim().split(",")));
				}
			}
		}
		return permsSet;
	}
	
}
